#pragma once
#include <QOpenGLWidget>
#include <QOpenGlShaderProgram>
#include <QOpenGlFunctions>
#include <QOpenGLVertexArrayObject>

class GlWidget;
class QOpenGLTexture;
class Surface : public QObject
{
	Q_OBJECT
protected:
	Surface();
	~Surface();

public:
	void setPoint(const QPoint &point);
	QPoint getPoint() const;

	void setSize(const QSize &size);
	QSize getSize() const;

	void setSelect(bool select);
	bool getSelect() const;

	void setImage(const QImage& image);
	QImage getImage() const;

protected:
	void draw();
	void updateVbo();
	void updateShapeVbo();
	void updateTextureVbo();
	void setGlWidget(GlWidget* w);

private:
	static void initShader();

signals:
	void rectChanged(const QRect& rt);
	void selectChanged(bool select);

private:
	QPoint m_point;
	QSize m_size;
	GLuint m_shapeVertexVbo;
	GLuint m_shapeClrVbo;
	GLuint m_textureVertexVbo;
	GLuint m_textureCoordVbo;
	GLuint m_textureId;
	QOpenGLTexture* m_texture;
	bool m_select = false;
	QOpenGLVertexArrayObject m_vao;
	GlWidget* m_glWidget = nullptr;
	QImage m_image;
	static QOpenGLShaderProgram *m_shapeProgram;
	static int m_shapePosAttrib;
	static int m_shapeColorAttrib;
	static QOpenGLShaderProgram* m_textureProgram;
	static int m_texturePosAttrib;
	static int m_textureTextCoordAttrib;

	friend class GlWidget;
};

class GlWidget : public QOpenGLWidget, public QOpenGLFunctions
{
	Q_OBJECT
public:
	GlWidget();
	~GlWidget();

public:
	Surface* addSurface();
    void removeSurface(Surface* s);
	QList<Surface*> getSurfaces();

protected:
	virtual void initializeGL() override;
	virtual void resizeGL(int w, int h) override;
	virtual void paintGL() override;

	virtual void mouseMoveEvent(QMouseEvent* event) override;
	virtual void mousePressEvent(QMouseEvent* event) override;
	virtual void mouseReleaseEvent(QMouseEvent* event) override;

signals:
	void surfaceAdded(Surface* s);
	void surfaceRemoved(Surface* s);

private:
	QList<Surface*> m_surfaces;
	QPoint m_mousePos;
	bool m_mousePressed = false;
	QMap<Surface*, QPoint> m_surfaceMousePosMap;

	friend class Surface;
};

